<!--
 * @Description: 1分钱商品专区商品编辑
 * @Author: Li Yujie
 * @Date: 2020/12/22
 * @Last Modified by: Li Yujie
 * @Last Modified time: 2020/12/22
-->
<template>
    <div class="wrapper">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    {{ type === 'add' ? '添加1分钱商品' : '编辑1分钱商品' }}
                </div>
            </div>
            <!-- /header -->

            <!--表单-->
            <el-form
                :model="ruleForm"
                :rules="rules"
                label-position="right"
                ref="ruleForm"
                label-width="120px"
                class="form-wrap"
            >
                <div class="form-title">选择商品信息</div>
                <el-form-item
                    label=""
                    prop="goods_no"
                    label-width="32px"
                >
                    <div class="select-goods-view">
                        <template v-if="type === 'add'">
                            <div
                                class="select-goods"
                                v-if="!ruleForm.goods_no"
                                @click="$refs.goodsSelect.show(1, requestUrl, typeList)"
                            >
                                <i class="el-icon-plus"/>
                                <div>点击选择商品</div>
                            </div>
                            <div
                                class="select-goods selected"
                                v-else
                                @click="$refs.goodsSelect.show(1, requestUrl, typeList)"
                            >
                                <el-image
                                    :src="ruleForm.goods_cover"
                                    fit="cover"
                                >
                                    <div
                                        slot="error"
                                        class="image-slot"
                                    >
                                        <i class="el-icon-picture-outline"/>
                                    </div>
                                </el-image>
                            </div>
                        </template>
                        <template v-else>
                            <div class="select-goods detail">
                                <el-image :src="ruleForm.goods_cover">
                                    <div
                                        slot="error"
                                        class="image-slot"
                                    >
                                        <i class="el-icon-picture-outline"/>
                                    </div>
                                </el-image>
                            </div>
                        </template>
                        <div class="select-goods-info">
                            <div class="goods-info-item">
                                <div class="goods-info__label">商品原标题</div>
                                <div class="goods-info__value">
                                    <el-input
                                        v-model="ruleForm.goods_title"
                                        disabled
                                        size="medium"
                                    />
                                </div>
                            </div>
                            <div class="goods-info-item">
                                <div class="item">
                                    <div class="goods-info__label">商品ID</div>
                                    <div class="goods-info__value">
                                        <el-input
                                            v-model="ruleForm.goods_no"
                                            disabled
                                            size="medium"
                                        />
                                    </div>
                                </div>
                                <div class="item">
                                    <div class="goods-info__label">商品标题</div>
                                    <div class="goods-info__value">
                                        <el-form-item
                                            prop="goods_title_free"
                                        >
                                            <el-input
                                                v-model="ruleForm.goods_title_free"
                                                size="medium"
                                                placeholder="选填，请输入商品标题"
                                            />
                                        </el-form-item>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <div class="form-title">活动库存和补贴方式设置</div>
                <el-form-item label-width="32px">
                    <el-table
                        :data="ruleForm.price_list"
                        :height="400"
                        style="width: 100%;border: 1px solid #eee"
                        class="data-table product"
                        empty-text="暂无数据信息，请上方的“点击添加商品”进行添加"
                        @selection-change="handleSelectAll($event)"
                    >
                        <el-table-column
                            type="selection"
                            align="center"
                            width="48"
                        >
                            <template slot-scope="scope">
                                <el-form-item style="margin-bottom: 20px">
                                    <el-checkbox
                                        v-model="scope.row.check_status"
                                        :true-label="1"
                                        :false-label="0"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商品规格"
                            show-overflow-tooltip
                            :formatter="emptyFormatter"
                            width="200"
                        >
                            <template slot-scope="scope">
                                <el-form-item style="margin-bottom: 20px">
                                    {{ scope.row.spec_list | filterSpec }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="product_price"
                            label="原售价"
                            show-overflow-tooltip
                            align="center"
                            :formatter="emptyFormatter"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    {{ scope.row.product_price }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="活动库存"
                            width="240"
                        >
                            <template slot-scope="scope">
                                <div
                                    class="input-wrapper"
                                    style="display: flex; align-items: center;margin-bottom: 20px"
                                >
                                    <el-select
                                        v-model="scope.row.stock_type"
                                        :style="{width: scope.row.stock_type === 1 ? '138px' : '108px'}"
                                        size="medium"
                                        :disabled="scope.row.check_status === 0"
                                        @change="handleStockTypeChange($event, scope.$index)"
                                        @click.native="clickDisableInput(scope.row)"
                                    >
                                        <el-option
                                            label="同步商家库存"
                                            :value="1"
                                        />
                                        <el-option
                                            label="自定义"
                                            :value="2"
                                        />
                                    </el-select>
                                    <el-form-item
                                        v-if="scope.row.stock_type === 2"
                                        :prop="`price_list[${scope.$index}].product_stock_free`"
                                        :rules="rules.product_stock_free"
                                    >
                                        <el-input
                                            v-model.number="scope.row.product_stock_free"
                                            style="width: 88px;margin-left: 10px"
                                            size="medium"
                                            :disabled="scope.row.check_status === 0"
                                            @click.native="clickDisableInput(scope.row)"
                                        />
                                    </el-form-item>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="product_stock"
                            label="实际库存"
                            show-overflow-tooltip
                            align="center"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    {{ scope.row.product_stock }}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="是否平台补贴"
                            align="center"
                            width="200px"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    style="margin-bottom: 20px"
                                >
                                    <el-select
                                        v-model="scope.row.shop_subsidy_enable"
                                        size="medium"
                                        style="width: 140px"
                                        :disabled="scope.row.check_status === 0"
                                        @click.native="clickDisableInput(scope.row)"
                                        @change="handleSubsidyChange($event, scope.$index)"
                                    >
                                        <el-option
                                            label="平台补贴"
                                            :value="1"
                                        />
                                        <el-option
                                            label="商家全部补贴"
                                            :value="0"
                                        />
                                        <el-option
                                            label="商家部分补贴"
                                            :value="2"
                                        />
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="商家补贴金额（元）"
                            align="center"
                            width="200px"
                        >
                            <template slot-scope="scope">
                                <el-form-item
                                    :prop="`price_list[${scope.$index}]`"
                                    :rules="rules.shop_subsidy_money_by_shop"
                                    style="margin-bottom: 20px"
                                >
                                    <el-input
                                        v-model="scope.row.shop_subsidy_money_by_shop"
                                        placeholder="商家补贴金额"
                                        size="medium"
                                        clearable
                                        style="width: 120px"
                                        @click.native="clickDisableInput(scope.row)"
                                        :disabled="scope.row.shop_subsidy_enable !== 2 || scope.row.check_status === 0"
                                    />
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item
                    label="排序号"
                    prop="goods_sort_free"
                >
                    <el-input
                        oninput="value = value.replace(/[^\d]/g,'')"
                        v-model.number="ruleForm.goods_sort_free"
                        size="medium"
                        clearable
                        style="width: 218px"
                    />
                    <span class="tips">在一卡通专区显示的位置，越小越靠前</span>
                </el-form-item>
                <el-form-item
                    label="限领设置"
                    prop="goods_buy_limit_free"
                >
                    每个会员月限领
                    <el-input
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        type="text"
                        v-model.number="ruleForm.goods_buy_limit_free"
                        size="medium"
                        :style="{width: '127px',marginLeft: '6px'}"
                    >
                        <p
                            slot="suffix"
                            :style="{color: 'rgba(102, 102, 102, 1)', marginRight: '5px'}"
                        >
                            个
                        </p>
                    </el-input>
                </el-form-item>
                <el-form-item
                    label="活动状态设置"
                >
                    <el-switch
                        v-model="ruleForm.goods_status_free"
                        active-text="上架"
                        inactive-text="下架"
                        :active-value="1"
                        :inactive-value="0"
                    />
                </el-form-item>

            </el-form>
            <!--/表单-->

            <div class="btn-group">
                <el-button
                    size="medium"
                    style="width: 120px"
                    @click="handleCancel()"
                >取消
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    style="width: 120px"
                    @click="handleSubmit()"
                >完成
                </el-button>
            </div>
        </div>

        <!--商品选择弹窗-->
        <goods-select
            ref="goodsSelect"
            @change="handleSelectGoods"
        />
        <!-- 图片预览 -->
        <img-preview ref="preview"/>

        <!-- 预算提示弹窗 -->
        <show-dialog
            ref="showDialog"
            :dialog="showDialog"
            :width="360"
            :cancel-text="'取消'"
            :confirm-text="'确定'"
            :title="'温馨提示'"
            :content="`当前新人专区的平台补贴支出在计划时间${ '2021/5/24-2021/6/24' }已无预算，暂无法添加新人专区商品`"
            @close="showDialog = false"
            @emit="() => {
                this.$router.push({
                    path: '/student/zero-area-list'
                });
            }"
        />
    </div>
</template>

<script>
/**
 * 页面接收参数
 * @param no - 商品编号
 */
import showDialog from '@/components/common/dialog.vue';
import {back} from '@/mixin/back';
import GoodsSelect from '@/components/goods/goods-select';
import imgPreview from '@/components/common/img-preview';

export default {
    name: "ZeroGoodsEdit",
    data() {
        const validateMemberGoodsCount = (rule, value, callback) => {
            if (this.ruleForm.memberGoodsType === 2 && value === '') {
                callback(new Error('请填写1分钱商品专区每月限领数量'));
            } else {
                callback();
            }
        };

        return {
            ruleForm: {
                // 商品编号
                goods_no: '',
                // 原商品标题
                goods_title: '',
                goods_title_free: '',
                // 商品原价
                goods_price: '',
                // 封面图
                goods_cover: '',
                // 排序号
                goods_sort_free: 99,
                // 上架状态
                goods_status_free: 0,
                // 规格价格列表
                price_list: [],
                goods_buy_limit_free: 0,
            },
            // 校验规则
            rules: {
                goods_no: [
                    {required: true, message: '请选择商品', trigger: 'blur'}
                ],
                goods_title_free: [
                    {required: true, message: '商品标题不能为空', trigger: 'blur'}
                ],
                goods_sort_free: [
                    {required: true, message: '排序号不能为空', trigger: 'blur'}
                ],
                product_stock_free: [
                    {required: true, message: '活动库存不能为空', trigger: 'blur'}
                ],
                goods_buy_limit_free: [
                    {validator: validateMemberGoodsCount, trigger: 'blur'}
                ],
            },
            type: 'add',
            // 商品弹窗类型
            typeList: [
                {label: '自营', value: 1},
                {label: '折扣', value: 5},
            ],
            requestUrl: '/student/shop_vip_free%5Cget_depot_goods_list',
            showDialog: false
        };
    },
    mixins: [back],
    filters: {
        filterSpec (val) {
            if(!val) return '';
            let str = '';

            val.forEach(el => {
                str += el.spec_name + ':' + el.spec_value + '；';
            });
            return str;
        }
    },
    components: {
        GoodsSelect,
        imgPreview,
        showDialog
    },
    mounted() {
        let query = this.$route.query;

        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {
            title: '1分钱商品专区',
            path: '/student/zero-area-list'
        }, {title: query.type === 'add' ? '添加1分钱商品' : '编辑1分钱商品'}]);
        this.type = query.type;
        if (query.no) {
            this.ruleForm.goods_no = query.no;
            this.getDetail();
        }
    },
    methods: {
        /**
         * 获取选择的商品
         * @param val
         */
        handleSelectGoods(val) {
            this.ruleForm.goods_title = val.goods_title;
            this.ruleForm.goods_title_free = val.goods_title;
            this.ruleForm.goods_no = val.goods_no;
            this.ruleForm.goods_price = val.goods_price;
            this.ruleForm.goods_cover = val.goods_cover;
            this.goods_no = val.goods_no;
            val.product_list.forEach(item => {
                this.$set(item, 'check_status', 0);
                this.$set(item, 'stock_type', 1);
                this.$set(item, 'product_stock_free', -1);
                this.$set(item, 'shop_subsidy_enable', 1);
                this.$set(item, 'shop_subsidy_money_by_shop', 0);
            });
            this.ruleForm.price_list = val.product_list;
        },

        /**
         * 查看图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         */
        fnShowPreview(images) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 提交
         */
        handleSubmit() {
            this.$refs.ruleForm.validate((valid) => {

                if (valid) {
                    let params = {...this.ruleForm};

                    params.product_json = JSON.stringify(params.price_list);
                    delete params.price_list;
                    this.$post('/student/shop_vip_free%5Csave', params, resp => {
                        if (resp.code === 1) {
                            if(resp.data.result === 1) {
                                this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        path: '/student/zero-area-list'
                                    });
                                }, 500);
                            } else {
                                this.$zdConfirm(`当前一卡通1分钱专区的平台补贴支出${resp.data.result === -1 ? '不在财控计划时间内' : '在计划时间已无预算'} ，暂无法添加一卡通1分钱商品，如需要增加预算，请联系平台财务人员。`, '温馨提示', {
                                    confirmButtonText: '知道了',
                                    hasCancelButton: false,
                                    type: 'warning'
                                }).then(() => {});
                            }
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });

                }
            });
        },

        /**
         * 返回列表
         */
        handleCancel() {

            this.$confirm('返回后将不会保存您所修改的内容,是否返回?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$router.push({
                    path: '/student/zero-area-list'
                });
            });
        },

        /**
         * 编辑时获取详情
         */
        getDetail() {

            let params = {
                goods_no: this.ruleForm.goods_no
            };

            this.$post('/student/shop_vip_free%5Cget', params, resp => {
                if (resp.code === 1) {
                    this.ruleForm.goods_no = resp.data.goods_no;
                    this.ruleForm.goods_price = resp.data.goods_price;
                    this.ruleForm.goods_title = resp.data.goods_title;
                    this.ruleForm.goods_sort_free = resp.data.goods_sort_free;
                    this.ruleForm.goods_status_free = resp.data.goods_status_free;
                    this.ruleForm.goods_title_free = resp.data.goods_title_free;
                    this.ruleForm.goods_buy_limit_free = resp.data.goods_buy_limit_free;
                    this.ruleForm.limit_type = resp.data.goods_buy_limit_free ? 2 : 1;

                    this.getProductList();
                    this.getGoodsInfo(resp.data.goods_no);
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 详情时获取产品规格信息
         */
        getProductList() {
            let params = {
                goods_no: this.ruleForm.goods_no,
            };

            this.$post('/student/shop_vip_free%5Cget_product_list', params, resp => {
                if (resp.code === 1) {
                    resp.data.product_list.forEach(item => {
                        if(item.product_stock_free === -1) {
                            item.stock_type = 1;
                        } else {
                            item.stock_type = 2;
                        }
                    });
                    this.ruleForm.price_list = resp.data.product_list;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 全选
         * @param selection
         */
        handleSelectAll(selection) {
            this.ruleForm.price_list.forEach(item => {
                this.$set(item, 'check_status', selection.length ? 1 : 0);
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 选择库存类型
         * @param val
         * @param index
         */
        handleStockTypeChange(val, index) {
            if(val === 1) {
                this.ruleForm.price_list[index].product_stock_free = -1;
            } else {
                this.ruleForm.price_list[index].product_stock_free = 0;
            }
        },

        /**
         * 是否平台补贴切换
         * @param val
         * @param index
         */
        handleSubsidyChange(val, index) {
            if(val === 1) {
                this.ruleForm.price_list[index].shop_subsidy_money_by_shop = 0;
            }
        },

        /**
         * 点击禁用的input
         * @param row
         */
        clickDisableInput(row) {
            if(!row.check_status) {
                this.$message.warning('请勾选该规格');
            }
        },

        /**
         * 获取商品信息
         * @param goods_no
         */
        getGoodsInfo(goods_no) {
            let params = {
                goods_nos: goods_no
            };

            this.$post('/student/shop_goods%5Cget_list_for_select', params, resp => {
                if (resp.code === 1) {
                    let data = resp.data.list[0];

                    this.ruleForm.goods_cover = data.goods_cover;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning'
                    });
                }
            });
        }
    }
};
</script>

<style scoped lang="less">
.wrapper {
    width: 100%;

    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;
        background: #fff;
        box-sizing: border-box;
        overflow-y: auto;

        /*header*/

        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #F0F2F5;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }

        /*表单*/

        .form-wrap {
            margin: 24px;
            padding: 24px 32px;
            background: #FBFBFB;
            border-radius: 2px;
            border: 1px solid #EEEEEE;
            .form-title {
                font-size: 16px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #333333;
                padding-bottom: 12px;
                border-bottom: 1px solid #E9E9E9;
                margin-bottom: 24px;
            }
            .select-goods-view {
                display: flex;
                height: 148px;
                margin-bottom: 32px;
                .select-goods {
                    width: 148px;
                    height: 148px;
                    background: #FFFFFF;
                    border-radius: 4px;
                    border: 1px solid #20A0FF;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #20A0FF;
                    cursor: pointer;
                    margin-right: 32px;
                    .el-icon-plus {
                        font-size: 48px;
                        margin-bottom: 8px;
                    }
                    &.detail {
                        border: 0;
                    }
                    .el-image {
                        width: 100%;
                        height: 100%
                    }
                    &.selected {
                        border: 0;
                        position: relative;
                        &:hover {
                            &::after {
                                content: "";
                                position: absolute;
                                width: 148px;
                                height: 148px;
                                background: rgba(0, 0, 0, 0.6);
                                border-radius: 4px;
                                left: 0;
                                top: 0;
                                display: flex;
                            }
                            &::before {
                                content: "重新选择";
                                position: absolute;
                                width: 112px;
                                height: 36px;
                                background: #FFFFFF;
                                border-radius: 18px;
                                z-index: 1;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                font-size: 14px;
                                font-family: PingFangSC-Medium, PingFang SC;
                                font-weight: 500;
                                color: #20A0FF;
                            }
                        }
                    }
                }
                .select-goods-info {
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    flex: 1;
                    .goods-info-item {
                        &:first-child {
                            flex-direction: column;
                        }
                        display: flex;
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #555555;
                        margin-bottom: 12px;
                        .item {
                            flex: 1;
                            &:first-child {
                                margin-right: 24px;
                            }
                        }
                        .goods-info__value {
                            color: #999999;
                        }
                    }
                }
            }

            .zd-spec {
                display: flex;
                font-size: 14px;
                padding-right: 12px;

                .zd-spec-luck-text {
                    margin-right: 10px;
                }
            }

            /deep/ .el-checkbox-group {
                display: flex;
                flex-direction: column;

                .zd-spec {
                    display: flex;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;

                    .zd-spec-text {
                        font-size: 14px;
                        margin-right: 10px;
                    }
                }

                .el-checkbox {
                    width: min-content;
                }
            }

            .tips {
                margin-left: 24px;
                font-size: 14px;
                color: #999;
            }

            .el-radio-group-wrap {
                display: flex;
                flex-direction: column;
                margin-top: 12px;

                .el-radio {
                    display: flex;
                }
            }
        }

        .btn-group {
            margin-left: 120px;
            padding-bottom: 36px;

            .el-button {
                margin: 0 24px;
            }
        }
    }
    /deep/ .el-table {
        th {
            background: #f2f2f2!important;
        }
        td {
            border-bottom: 0!important;
            background: #FBFBFB!important;
        }
    }
    /deep/ .el-table.product {
        background: #FBFBFB!important;
        .el-table__body-wrapper {
            padding-top: 12px;
        }
    }
    /deep/ .el-table__body-wrapper::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background-color: #a1a3a9;
    }

    ::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #a1a3a9;
        border-radius: 3px;
    }
    /deep/ .el-table {
        border: 1px solid #eee;
        border-radius: 4px;

        th {
            background: #f2f2f2 !important;
        }

        td {
            background: #FBFBFB !important;
            border-bottom: 0;
        }

        .el-table__row.cursor {
            cursor: pointer;
        }
        .el-table__empty-block {
            background: #FBFBFB
        }
        .el-table__body-wrapper {
            background: #FBFBFB
        }
    }
}
</style>
